package cn.heycm.blog.common.entity.result;

import lombok.Getter;

/**
 * Web 统一响应格式
 *
 * @author hey
 * @version 1.0
 * @since 2024/9/15 15:30
 */
@Getter
public class Result<T> {

    public static final Result SUCCESS = Result.success();

    public static final Result ERROR = Result.error(CodeMsg.UNKNOWN_ERROR);

    /**
     * 状态码
     */
    private int code;

    /**
     * 消息
     */
    private String msg;

    /**
     * 数据
     */
    private T data;

    public static <T> Result<T> success() {
        Result<T> result = new Result<>();
        result.code = CodeMsg.SUCCESS.getCode();
        result.msg = CodeMsg.SUCCESS.getMsg();
        return result;
    }

    public static <T> Result<T> success(T data) {
        Result<T> result = Result.success();
        result.data = data;
        return result;
    }

    public static <T> Result<T> error(CodeMsg codeMsg) {
        Result<T> result = new Result<>();
        result.code = codeMsg.getCode();
        result.msg = codeMsg.getMsg();
        return result;
    }

    public static <T> Result<T> error(int code, String msg) {
        Result<T> result = new Result<>();
        result.code = code;
        result.msg = msg;
        return result;
    }

    public static <T> Result<T> error(String msg) {
        Result<T> result = new Result<>();
        result.code = CodeMsg.UNKNOWN_ERROR.getCode();
        result.msg = msg;
        return result;
    }

    public boolean isSuccess() {
        return this.code == Result.SUCCESS.code;
    }
}
